package jp.aist.gtrc.plus.admission.command;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import jp.aist.gtrc.plus.admission.*;
import jp.aist.gtrc.plus.admission.EDF.JobArray;
import jp.aist.gtrc.plus.scheduler.util.TimeUtil;


public class FeasibilityTester {
        private static String hostname = "localhost";

        protected static AdmissionServer getAdmissionServer() throws AdmissionException {
           if (System.getSecurityManager() == null) 
              System.setSecurityManager(new AdmissionSecurityManager()); 

           int rmiPort = Registry.REGISTRY_PORT;

           try {
              Registry registry = LocateRegistry.getRegistry(hostname,rmiPort);
System.out.println(registry);
              AdmissionServer admissionServer = (AdmissionServer) registry.lookup(AdmissionServer.RMI_OBJ_NAME);
              return admissionServer;
           } catch (Exception e) {
              throw new AdmissionException("Cannot connect to rmi://" + hostname + ":" + rmiPort);
           }
        } 

	public static void main(String[] args) throws Exception {

		AdmissionServer admissionServer = null;

		try {
                        if (args.length == 4) {
                           hostname = args[3];
                        }
			admissionServer = getAdmissionServer();
                        int jobNum = Integer.parseInt(args[0]);
                        int exeTime = Integer.parseInt(args[1]);
                        Calendar calendar = TimeUtil.makeCalendarFromPOSIX(args[2]);
                        if (calendar == null) {
                           usage();
                           throw new RuntimeException("Wrong POSIX date time format");
                        }
                        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMddHHmm");
                        String posixDateTime = dateFormater.format(calendar.getTime());
                        Calendar currentTime = Calendar.getInstance();
                        int deadline = (int) (calendar.getTimeInMillis() - currentTime.getTimeInMillis())/ 1000; 
                        JobArray jobArray = new JobArray("NewJob",jobNum,exeTime,deadline);
                        System.out.print("Testing if the job can be completed by " + posixDateTime + ": " );
			boolean isOK = admissionServer.isFeasible(jobArray);
			System.out.println(isOK);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}

	}

        public static void usage() {
           FeasibilityTester tester = new FeasibilityTester();
           System.err.println("Usage: classname  <#jobs>  <time> <deadline> [hostname]");
           System.err.println("      time in seconds.");
           System.err.println("      deadline in [[[[CC]YY]MM]DD]hhmm[.SS] format.");
        }

}
